package exhi.action;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.stp.core.entity.IGridRowFactory;
import com.stp.core.entity.XGrid;
import com.stp.core.entity.XGridPage;
import com.stp.core.entity.XGridRow;
import com.stp.core.entity.XMsg;

import exhi.entity.EntpStock;
import exhi.entity.EntpUser;

@Controller
@RequestMapping("/entp")
public class AdminEntpAct extends BaseAct {

	private static final String PATH_TABLE = "/entp-table";
	private static final String PATH_LIST = "/entp-list";
	private static final String PATH_DETAIL = "/entp-detail";
	private static final String PATH_AUDIT = "/entp-audit";
	private static final String PATH_AUDIT_SAVE = "/entp-audit-save";
	private static final String PATH_SAVE = "/entp-save";
	private static final String PATH_DELETE = "/entp-delete";

	// 企业注册信息修改保存
	private static final String PATH_CORP_DETAIL = "/corp-detail";
	private static final String PATH_CORP_SAVE = "/corp-save";
	private static final String PATH_CORP_MSG = "/entp/corp-msg";

	private static final String PATH_STOCK_LIST = "/stock-list";
	private static final String PATH_STOCK = "/stock-info";
	private static final String PATH_STOCK_SAVE = "/stock-save";

	@RequestMapping(PATH_TABLE)
	public void table() {
	}

	@RequestMapping(PATH_LIST)
	@ResponseBody
	public String list(XGridPage page) {
		EntpGridRow row = new AdminEntpAct.EntpGridRow();
		String sql = " from EntpUser s where 1=1 ";
		XGrid grid = entpMng.getXGrid(sql, row, page.getPageNo(),
				page.getPageSize(), false);
		if (null == grid)
			return "";
		return "{\"xGrid\":" + toJson(grid) + "}";
	}

	@RequestMapping(PATH_DETAIL)
	public String entpDetail(@ModelAttribute("entpUser") EntpUser entpUser,
			ModelMap model) {
		model.addAttribute("entpUser", entpUser);
		model.addAttribute("entpId", entpUser.getUid());
		if ("C".equalsIgnoreCase(entpUser.getDwlx())) {
			return "entp/corp-c";
		}
		if ("S".equalsIgnoreCase(entpUser.getDwlx())) {
			return "entp/corp-s";
		}
		if ("X".equalsIgnoreCase(entpUser.getDwlx())) {
			return "entp/corp-x";
		}
		return PATH_DETAIL.substring(1);
	}

	// json数据
	@RequestMapping(PATH_DELETE)
	@ResponseBody
	public String delete(
			@RequestParam(value = "ids", required = true, defaultValue = "") String ids,
			ModelMap model) {
		delete("t_entp_user", "uid", ids);
		delete("std_rbac_user", "user_Id", ids);
		XMsg msg = new XMsg();
		msg.setState(true);
		return toJson(msg);
	}

	@RequestMapping(PATH_AUDIT)
	public String entpAudit(@ModelAttribute("entpUser") EntpUser entpUser,
			ModelMap model) {
		model.addAttribute("entpUser", entpUser);
		model.addAttribute("entpId", entpUser.getUid());
		if ("C".equalsIgnoreCase(entpUser.getDwlx())) {
			return "entp/corp-ac";
		}
		if ("S".equalsIgnoreCase(entpUser.getDwlx())) {
			return "entp/corp-as";
		}
		if ("X".equalsIgnoreCase(entpUser.getDwlx())) {
			return "entp/corp-ax";
		}
		return PATH_AUDIT.substring(1);
	}

	@RequestMapping(PATH_CORP_DETAIL)
	public String corpDetail(ModelMap model) {
		EntpUser entpUser = getEntpUser();
		// 无效登陆
		if (null == entpUser)
			return "redirect:../browser/index.jspx";
		model.addAttribute("entpUser", entpUser);
		model.addAttribute("entpId", entpUser.getUid());
		if ("C".equalsIgnoreCase(entpUser.getDwlx())) {
			return "entp/corp-vc";
		}
		if ("S".equalsIgnoreCase(entpUser.getDwlx())) {
			return "entp/corp-vs";
		}
		if ("X".equalsIgnoreCase(entpUser.getDwlx())) {
			return "entp/corp-vx";
		}
		return PATH_CORP_DETAIL.substring(1);
	}

	@ModelAttribute("entpUser")
	public EntpUser getEntpUser(
			@RequestParam(value = "entpId", required = true, defaultValue = "") String id) {
		EntpUser info = entpMng.get(id);
		if (null == info) {
			info = new EntpUser();
		}
		return info;
	}

	@RequestMapping(PATH_CORP_SAVE)
	@ResponseBody
	public String corpSave(@ModelAttribute("entpUser") EntpUser entpUser,
			@RequestParam("entpId") String entpId, ModelMap model)
			throws IllegalStateException, IOException {
		XMsg msg = new XMsg();
		entpMng.save(entpUser);
		msg.setMsg("保存成功");
		return toJson(msg);
	}

	@RequestMapping(PATH_SAVE)
	public String registerSave(HttpServletRequest request,
			@ModelAttribute("entpUser") EntpUser entpUser,
			@RequestParam("entpId") String entpId, ModelMap model)
			throws IllegalStateException, IOException {
		XMsg msg = new XMsg();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 执照
		if (saveUpload(multipartRequest, "attach1")) {
			attachMng.saveFileAttach(entpId, "CORPCERT0");//
		} else {
			msg.setState(false);
			msg.setMsg(attachMng.getErrors());
			model.addAttribute("msg", msg);
			return PATH_CORP_MSG.substring(1);
		}
		// 法人身份证
		if (saveUpload(multipartRequest, "attach2")) {
			attachMng.saveFileAttach(entpId, "CORPCERT1");
		} else {
			msg.setState(false);
			msg.setMsg(attachMng.getErrors());
			model.addAttribute("msg", msg);
			return PATH_CORP_MSG.substring(1);
		}
		// 经营人身份证
		if (saveUpload(multipartRequest, "attach3")) {
			attachMng.saveFileAttach(entpId, "CORPCERT2");
		} else {
			msg.setState(false);
			msg.setMsg(attachMng.getErrors());
			model.addAttribute("msg", msg);
			return PATH_CORP_MSG.substring(1);
		}
		entpMng.save(entpUser);
		msg.setMsg("保存成功");
		model.addAttribute("msg", msg);
		return PATH_CORP_MSG.substring(1);
	}

	// 股权列表
	@RequestMapping(PATH_STOCK_LIST)
	@ResponseBody
	public String stockList(XGridPage page,
			@RequestParam("entpId") String entpId) {
		StockGridRow row = new AdminEntpAct.StockGridRow();
		String sql = " from EntpStock s where 1=1 ";
		sql += sqlModel.getSQLChars("s.uid", "=", entpId, false, " and ");
		XGrid grid = entpMng.getStockGrid(sql, row, page.getPageNo(),
				page.getPageSize(), false);
		if (null == grid)
			return "";
		return "{\"xGrid\":" + toJson(grid) + "}";
	}

	// 股权信息
	@RequestMapping(PATH_STOCK)
	public void stockInfo(@RequestParam("entpId") String entpId,
			@ModelAttribute("entpStock") EntpStock stock, ModelMap model) {
		model.addAttribute("entpId", entpId);
		model.addAttribute("entpStock", stock);
	}

	@RequestMapping(PATH_STOCK_SAVE)
	public String stockSave(HttpServletRequest request,
			@RequestParam("entpId") String entpId,
			@ModelAttribute("entpStock") EntpStock stock, ModelMap model)
			throws IllegalStateException, IOException {
		XMsg msg = new XMsg();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 获得第1张图片（根据前台的name名称得到上传的文件）
		MultipartFile attach = multipartRequest.getFile("attachment");
		if (null != attach && attach.getSize() > 0) {
			if (attach.getSize() > 5242880) {
				msg.setState(false);
				msg.setMsg("上传附件不能超过5兆");
				model.addAttribute("msg", msg);
				return "msg";
			}
			String path = request.getSession().getServletContext()
					.getRealPath("/attachment/"); // 获取文件的保存路径
			String originalFileName = attach.getOriginalFilename(); // 原始的文件名
			String uniqueFileName = entpId + "_"
					+ String.valueOf(System.currentTimeMillis()); // 将文件重新命名，反正重复
			String extensionName = StringUtils.substringAfterLast(
					originalFileName, "."); // 获取扩展名
			List<String> fileTypes = new ArrayList<String>();
			fileTypes.add("jpg");
			fileTypes.add("jpeg");
			fileTypes.add("bmp");
			fileTypes.add("png");
			fileTypes.add("gif");
			if (fileTypes.contains(extensionName.toLowerCase())) {
				attach.transferTo(new File(path + "/" + uniqueFileName + "."
						+ extensionName)); // 文件上传
				stock.setGdsfz("attachment/" + uniqueFileName + "."
						+ extensionName);
			} else {
				msg.setState(false);
				msg.setMsg("不支持此文件类型上传");
				model.addAttribute("msg", msg);
				return "msg";
			}
		}
		if (null == stock.getUid())
			stock.setUid(entpId);
		entpMng.saveStock(stock);
		model.addAttribute("msg", msg);
		return "msg";
	}

	@ModelAttribute("entpStock")
	public EntpStock getEntpStock(
			@RequestParam(value = "stockId", required = true, defaultValue = "0") String id) {
		if ("".equalsIgnoreCase(id))
			id = "0";
		EntpStock info = entpMng.getStock(new Integer(id));
		if (null == info) {
			info = new EntpStock();
		}
		return info;
	}

	class StockGridRow implements IGridRowFactory {
		public XGridRow builderXRow(Object obj) {
			// TODO Auto-generated method stub
			XGridRow xrow = null;
			if (obj instanceof EntpStock) {
				xrow = new XGridRow();
				EntpStock info = (EntpStock) obj;
				xrow.setId(info.getId().toString());
				List t = new ArrayList();
				t.add("");
				t.add(info.getGdxm());
				t.add(info.getSfzh());
				if (info.getGdsfz() == null
						|| "".equalsIgnoreCase(info.getGdsfz())) {
					t.add("无");
				} else {
					t.add("<a target='blank' href='./" + info.getGdsfz()
							+ "'>【查看】</a>");
				}

				t.add("<a href='#' onclick='changeStock(" + info.getId()
						+ ");'>【编辑】</a>");
				xrow.setData(t);
			}
			return xrow;
		}
	}

	class EntpGridRow implements IGridRowFactory {
		public XGridRow builderXRow(Object obj) {
			// TODO Auto-generated method stub
			XGridRow xrow = null;
			if (obj instanceof EntpUser) {
				xrow = new XGridRow();
				EntpUser info = (EntpUser) obj;
				xrow.setId(info.getUid().toString());
				List t = new ArrayList();
				t.add("");
				t.add(info.getZzjgdm());
				t.add(info.getMc());
				t.add("<a href='entp-detail.jspx?entpId=" + info.getUid()
						+ "'>【修改】</a><a href='entp-audit.jspx?entpId="
						+ info.getUid() + "'>【进入黑名单】</a>");
				/*
				t.add("<a href='entp-detail.jspx?entpId=" + info.getUid()
						+ "'>【修改】</a> <a href='entp-audit.jspx?entpId="
						+ info.getUid() + "'>【审查】</a>");
				*/
				xrow.setData(t);
			}
			return xrow;
		}
	}
}
